/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: threadandsync_example.cpp,v 1.9 2009-05-13 07:18:25 amaula Exp $
 * \file
 * \brief CThread and CSync utility class example file.
 * \author Antti Maula <antti.maula@tkk.fi>
 */
#include "owndebug.h"
#include "thread.hpp"
#include "sync.hpp"
#include <stdlib.h>

//*****************************************************************************

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

/** Example class derived from CThread and CSync.
 *
 * \note Pay attention to construction order of CSync and CThread
 * class instances, as they are destructed in reverse order, they must
 * be initialized like this to guarantee mutex facilities for any
 * running threads!
 */
class MyTestClass : private gim::CSync, 
                    private gim::CThread
{
public:
  MyTestClass() 
    : CSync(1, 1),                // Maximum of 1 conditions and 1 Mutex
      CThread(10),                // Maximum of 10 threads
      iTargetValue(-1),
      iTotalGuesses(0)
  {
    dPrint(1,"Constructed instance %p of MyTestClass", this);
  }
  
  ~MyTestClass()
  {
    dPrint(1,"Destructed instance %p of MyTestClass", this);
  }
  
  /** Run the simple test.
   */
  void RunTest(void)
  {
    int i;
    bool r;

    // Init random generator
    srand(time(NULL));


    // Random value
    iTargetValue = random() % 255;
    dPrint(1,"Game begins - Target value is %d", iTargetValue);

    // Start threads
    for(i = 0; i < 10; ++i) {
      r = RunThread(i);
      dPrint(1,"Running player %d - %s", 
             i, r?"OK":"Failed!");
    }

    // Wait a moment
    ownSleep_ms(500);
    Notify(0, false);

    // Wait until threads exit
    for(i = 0; i < 10; ++i) {
      r = WaitThread(i);
      dPrint(1,"Waiting player %d - resulted in value %d", 
             i, r);
    }
  }

private:
  /** Thread running function.
   */
  int ThreadFunction(const int aThreadNumber) 
  {
    dPrint(1,"ThreadFunction for Player-%d Started.", aThreadNumber);
    
    while (IsRequestTermination() == false) {
      Lock();
      bool w = Wait(1000);
      if (w && IsRequestTermination() == false) {
        const int guess_value = random() % 255;
        ++iTotalGuesses;
        dPrint(1,"Thread-%d: My turn! Guessing value %d...%s (Total of %d guesses made)", 
               aThreadNumber, 
               guess_value, 
               guess_value == iTargetValue?"MATCH!":"Not a match...",
               iTotalGuesses);

        if (guess_value == iTargetValue) {
          dPrint(1,"Thread-%d Guessed it! Everybody can now exit!", 
                 aThreadNumber);
          
          // Terminate all threads.
          for(int i = 0; i < 10; ++i) {
            SetRequestTermination(i);
          }
        }
        
        Notify(0, false);
      }
      Unlock();
    } 
    
    dPrint(1,"ThreadFunction for Player-%d Stopped", aThreadNumber);

    return 0;
  }
  
  int iTargetValue;
  int iTotalGuesses;

};
//*****************************************************************************
//*****************************************************************************

int main(void)
{
  int result = 0;

  // Init debug facility & set level to 10
  debugInit();
  debugSetGlobalDebugLvl(1);

  printf("Test begin...\n");

  // Do testing
  MyTestClass mtc;
  mtc.RunTest();

  printf("Test done, Exit.\n");
  // Exit.
  return result;
}

//*****************************************************************************
